package com.hadwinling.blog.controller;

import com.hadwinling.blog.entity.Admin;
import com.hadwinling.blog.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;

/**
 * 管理者控制器
 * @author HadwinLing
 * @version V1.0
 * @Package com.hadwinling.blog.controller
 * @date 2020/8/19 7:47
 */
@Controller
@RequestMapping("/admin")
@SessionAttributes("currAdmin")
public class AdminController {
    @Autowired
    private AdminService adminService;

    @GetMapping("/")
    public String adminIndexPage(){
        return "AdminCenter/index";
    }


    @GetMapping("/login")
    public String toLoginPage(){
        return "AdminCenter/login";
    }

    @PostMapping("/login")
    public String login(String adminname,String password, Model model, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        Admin admin1 = adminService.selectOneByAdminnameAndPasswordAndState(adminname,password,1);
        System.out.println(admin1);
        if (admin1!=null){
            model.addAttribute("currAdmin",admin1);
            return "redirect:/admin/";
        }
        //密码错误
        return "redirect:/admin/login?rslt=1";

    }

    /**
     * 跳转到新增管理员界面
     * @return
     */
    @GetMapping("/addAdmin")
    public String toAddAdminPage(){
        return "AdminCenter/register";
    }

    /**
     * 执行新增管理员操作
     * @param admin
     * @return
     */
    @PostMapping("/addAdmin")
    public String register(Admin admin){
//        System.out.println("admin:"+admin);
        //为该账号添加判断是否是管理者还是用户：0：表示用户
        admin.setIsadmin(1);
        admin.setState(1);
        admin.setPower(0);
        admin.setCreatetime(new Date());
        adminService.insertSelective(admin);
        return "redirect:/admin/account";
    }
}
